<template>
  <div class="common-container">
    <!-- 操作区域 -->
    <el-card class="operation-card">
      <div class="operation-buttons">
        <el-button type="primary" @click="openForm(null)">
          <el-icon><Plus /></el-icon> 新增条目
        </el-button>
        <el-input
          v-model="query.search"
          placeholder="输入关键字搜索条目标题"
          style="width: 250px; margin-left: 15px"
          clearable
          @keyup.enter="fetchData"
          @clear="fetchData"
        >
          <template #suffix>
            <el-icon class="el-input__icon" @click="fetchData">
              <Search />
            </el-icon>
          </template>
        </el-input>
        <el-select
          v-model="query.base_id"
          placeholder="所属知识库"
          clearable
          style="width: 200px; margin-left: 15px;"
          @change="fetchData"
        >
          <el-option
            v-for="b in basesForSelect"
            :key="b.id"
            :label="b.name"
            :value="b.id"
          />
        </el-select>
        <el-select
          v-model="query.status"
          placeholder="状态"
          clearable
          style="width: 120px; margin-left: 15px;"
          @change="fetchData"
        >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
          <el-option label="待审核" :value="2" />
        </el-select>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">

      <el-table :data="list" style="width: 100%" border stripe v-loading="loading">
        <el-table-column prop="id" type="index" width="80" />
        <el-table-column prop="title" label="条目标题" min-width="200" />
        <el-table-column prop="knowledge_base_id" label="所属知识库" width="150">
          <template #default="{ row }">
            <el-tag type="info" size="small">
              {{ getKnowledgeBaseName(row.knowledge_base_id) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="条目信息" min-width="280">
          <template #default="{ row }">
            <div class="item-info">
              <div v-if="row.keywords && row.keywords.length">
                <span class="info-label">关键词：</span>
                <el-tag v-for="keyword in row.keywords.slice(0, 3)"
                        :key="keyword"
                        size="small"
                        type="primary"
                        style="margin-right: 4px;">
                  {{ keyword }}
                </el-tag>
                <span v-if="row.keywords.length > 3">...</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column prop="updated_at" label="更新时间" width="180" />
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row }">
            <div class="action-container">
              <el-tooltip content="编辑" placement="top">
                <el-button
                  class="action-button"
                  type="primary"
                  circle
                  size="small"
                  @click="openForm(row)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="内容编辑" placement="top">
                <el-button
                  class="action-button"
                  type="warning"
                  circle
                  size="small"
                  @click="handleContentEdit(row)"
                >
                  <el-icon><Document /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  class="action-button"
                  type="danger"
                  circle
                  size="small"
                  @click="handleDelete(row)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50]"
          @current-change="fetchData"
          @size-change="fetchData"
        />
      </div>
    </el-card>

    <!-- 表单对话框 -->
    <el-dialog v-model="form.visible" title="知识条目" width="780px"      :modal="true"
    :append-to-body="true"
    :lock-scroll="true" destroy-on-close>
      <el-form :model="form.model" label-width="100px">
        <el-form-item label="知识库" required>
          <el-select v-model="form.model.knowledge_base_id" style="width: 100%">
            <el-option
              v-for="b in basesForSelect"
              :key="b.id"
              :label="b.name"
              :value="b.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" required>
          <el-input v-model="form.model.title" />
        </el-form-item>
        <el-form-item label="摘要">
          <el-input type="textarea" v-model="form.model.summary" rows="3" />
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="form.model.keywords" placeholder='JSON数组或逗号分隔，如 ["选课","系统"] 或 选课,系统' />
        </el-form-item>
        <el-form-item label="标签">
          <el-input v-model="form.model.tags" placeholder='JSON数组或逗号分隔，如 ["教务","帮助"] 或 教务,帮助' />
        </el-form-item>
        <el-form-item label="优先级">
          <el-input-number v-model="form.model.priority" :min="1" :max="10" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.model.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="2">待审核</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="form.visible=false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Edit, Delete, Document } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import {
  getKnowledgeItems, createKnowledgeItem, updateKnowledgeItem, deleteKnowledgeItem,
  getKnowledgeBases
} from '@/api/knowledge'

defineOptions({
  name: 'KnowledgeItemsPage'
})

const router = useRouter()
const loading = ref(false)
const list = ref([])
const basesForSelect = ref([])
const query = reactive({ search: '', base_id: '', status: '' })
const pagination = reactive({ current: 1, size: 10, total: 0 })
const form = reactive({
  visible: false,
  model: {
    id: null,
    knowledge_base_id: '',
    title: '',
    summary: '',
    content: '',
    keywords: '',
    tags: '',
    priority: 5,
    status: 1,
    source_type: 'manual',
    source_url: ''
  }
})

// 根据知识库ID获取知识库名称
const getKnowledgeBaseName = computed(() => {
  return (baseId) => {
    const base = basesForSelect.value.find(b => b.id == baseId)
    return base ? base.name : `知识库${baseId}`
  }
})

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    1: 'success',
    0: 'danger',
    2: 'warning'
  }
  return types[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const labels = {
    1: '启用',
    0: '禁用',
    2: '待审核'
  }
  return labels[status] || '未知'
}

// 获取知识条目列表
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      skip: (pagination.current - 1) * pagination.size,
      limit: pagination.size,
      search: query.search || undefined,
      base_id: query.base_id || undefined,
      status_filter: query.status === '' ? undefined : query.status,
    }
    const res = await getKnowledgeItems(params)
    list.value = res.data || []
    pagination.total = res.total || 0
  } catch (e) {
    console.error(e)
    ElMessage.error('获取知识条目失败')
  } finally {
    loading.value = false
  }
}

// 获取知识库列表用于选择
const fetchBases = async () => {
  try {
    const res = await getKnowledgeBases({ skip: 0, limit: 100 })
    basesForSelect.value = res.data || []
  } catch (e) {
    console.error(e)
    ElMessage.error('获取知识库列表失败')
  }
}

// 打开表单
const openForm = (row) => {
  if (row) {
    form.model = {
      ...row,
      keywords: Array.isArray(row.keywords)
        ? JSON.stringify(row.keywords)
        : (row.keywords || ''),
      tags: Array.isArray(row.tags)
        ? JSON.stringify(row.tags)
        : (row.tags || ''),
    }
  } else {
    form.model = {
      id: null,
      knowledge_base_id: '',
      title: '',
      summary: '',
      content: '',
      keywords: '',
      tags: '',
      priority: 5,
      status: 1,
      source_type: 'manual',
      source_url: ''
    }
  }
  form.visible = true
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!form.model.knowledge_base_id) {
    ElMessage.error('请选择知识库')
    return
  }
  if (!form.model.title.trim()) {
    ElMessage.error('请输入标题')
    return
  }

  const data = new URLSearchParams()
  data.set('knowledge_base_id', form.model.knowledge_base_id)
  data.set('title', form.model.title)
  data.set('content', '') // 默认为空，后续通过内容编辑功能维护
  if (form.model.summary) data.set('summary', form.model.summary)
  if (form.model.keywords) data.set('keywords', form.model.keywords)
  if (form.model.tags) data.set('tags', form.model.tags)
  data.set('source_type', 'manual') // 默认为手动
  data.set('priority', form.model.priority)
  data.set('status_value', form.model.status)

  try {
    if (form.model.id) {
      await updateKnowledgeItem(form.model.id, data)
    } else {
      await createKnowledgeItem(data)
    }
    ElMessage.success('保存成功')
    form.visible = false
    fetchData()
  } catch (err) {
    console.error(err)
    ElMessage.error('保存失败')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确认删除条目「${row.title}」吗？`, '提示', { type: 'warning' })
    await deleteKnowledgeItem(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (e) {
    console.error(e)
  }
}

// 内容编辑
const handleContentEdit = (row) => {
  router.push({
    name: 'KnowledgeContentEditFullscreen',
    params: { itemId: row.id }
  })
}

onMounted(async () => {
  await fetchBases()
  await fetchData()
})
</script>

<style scoped>
.common-container {
  padding: 20px;
  height: calc(100vh - 180px);
  display: flex;
  flex-direction: column;
}

.operation-card {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  align-items: center;
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-table) {
  flex: 1;
  overflow: auto;
}

.item-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.info-label {
  font-weight: bold;
  margin-right: 5px;
  color: #606266;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.action-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.action-button {
  font-size: 12px;
  border: none;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
</style>
